var mysql = require('mysql');
var config =require('../config')
class Mysql{
    constructor(){
        this.connection = mysql.createConnection(config.mysqlConfig);
        //打开链接
        this.connection.connect()
    }
    query(params){
        return new Promise((resolve,reject)=>{
            this.connection.query(params.sql,params.value,(error, results, fields)=>{
                if(error){
                    resolve( this.error(error.message,error.code))
                }else{
                    resolve(this.success(results))
                }
            })
        })
        
    }
    //成功获取数据时
    success(data=[],messages="请求成功"){
        config.ResponseResult.code=200;
        config.ResponseResult.message=messages;
        config.ResponseResult.data=data;
        return config.ResponseResult
    }
    //报错时
    error(messages="请求失败",code="", data=[]){
        config.ResponseResult.code=code;
        config.ResponseResult.message=messages;
        config.ResponseResult.data=data;
        return config.ResponseResult
    }
}

module.exports=new Mysql()